package com.woniuxueyuan.interceptor;

import com.alibaba.fastjson.JSON;
import com.woniuxueyuan.util.JWTUtil;
import com.woniuxueyuan.util.ResponseData;
import com.woniuxueyuan.util.ResponseEnum;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 校验登录拦截器
 * 1.实现 HandlerInterceptor  接口
 * 2：重写preHandle方法
 *
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    /**
     *
     * 实现步骤（校验jwt合法性）
     * 1：获取前端jwt（前端的jwt存在请求头中）
     * 2.用系统密钥解密jwt
     * 解不开直接拦截
     * 3：拿前端的jwt和redis对比（判断redis对应的jwt是否过期）
     * 如果过期了还是要拦截的
     * 4:给该jwt时间续期
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1:获取前端的jwt（从请求头中获取jwt）
        String headerJWT = request.getHeader("authorization");
        String jsonString = JSON.toJSONString(ResponseData.fail(ResponseEnum.NO_LOGIN));
        response.setContentType("application/json;charset=UTF-8");
        if(headerJWT==null){
            //拦截

            response.getWriter().print(jsonString);
            return false;
        }
        //2.用系统密钥解密jwt
        if( !JWTUtil.verifyJWT(headerJWT)){
            response.getWriter().print(ResponseData.fail(ResponseEnum.NO_LOGIN));
            //拦截
            response.getWriter().print(jsonString);
            return false;
        }
        //3 拿前端jwt和redis的jwt对比（判断redis对应的jwt是否过期）
        //根据key到redis查询
        Map userInfo = JWTUtil.getJWTUserInfo(headerJWT);
        Object id = userInfo.get("id");
        String redisJWT = stringRedisTemplate.opsForValue().get("JWT:"+id);
         if(!headerJWT.equals(redisJWT)){
             response.getWriter().print(jsonString);
             return false;
         }
         //4给该jwt时间续期
        stringRedisTemplate.expire("JWT:"+id,20, TimeUnit.DAYS);//给指定key加时间

        return true;
    }
}
